import {
  generateCrudPage,
  headerToolbar,
  bulkActions,
  listButtons,
} from "./sys_columns.ts";
import { parse } from "url";
import adminCrud from "./sys_admin_crud.ts";
import { db } from "../../../config/db/connectiondb.ts";
import { successResponse, errorResponse } from "../../helpers.ts";
const apiUrl = "/admin-api/system/admin_permissions";
import AdminPermissions from "../models/AdminPermissions.ts";
import {AdminPermissionsMenu} from "../models/AdminPermissionMenu.ts";
import AdminMenus from "../models/AdminMenus.ts";
export async function grid() {
  const list = {
    apiUrl: apiUrl,
    headerToolbar: await headerToolbar(apiUrl, form), //头部工具栏
    bulkActions: await bulkActions(), //批量操作
    filter: await filter(), //筛选
    //showIndex: false,//是否显示序号列
    columns: [
      { name: "id", label: "ID" },
      { name: "name", label: "名称" },
      { name: "slug", label: "标识" },
      { name: "http_method", label: "请求方式" },
      { name: "http_path", label: "路由" },
      { name: "created_at", label: "创建时间" },
      { name: "updated_at", label: "保存时间" },
      await listButtons({
        types: ["edit", "detail", "delete"],
        apiUrl: apiUrl,
        detail: detail,
        form: form,
      }),
    ],
  };
  return await generateCrudPage(list);
}

//表单配置
async function form() {
  return [
    { type: "input-text", name: "name", label: "名称", required: true },
    { type: "input-text", name: "slug", label: "标识", required: true },
    {
      type: "select",
      name: "parent_id",
      label: "父级",
      searchable: true,
      required: false,
      selectMode: "tree",
      options: await getPermissionsTreeOptions1(),
    },
    {
      type: "checkboxes",
      name: "http_method",
      label: "请求方式",
      options: [
        {
          value: "GET",
          label: "GET",
        },
        {
          value: "POST",
          label: "POST",
        },
        {
          value: "PUT",
          label: "PUT",
        },
        {
          value: "DELETE",
          label: "DELETE",
        },
        {
          value: "PATCH",
          label: "PATCH",
        },
        {
          value: "OPTIONS",
          label: "OPTIONS",
        },
        {
          value: "HEAD",
          label: "HEAD",
        },
      ],
      description: "不选则为ANY",
      joinValues: false,
      extractValue: true,
    },
    {
      type: "input-number",
      name: "custom_order",
      label: "排序",
      required: true,
      labelRemark: "升序排序",
      displayMode: "enhance",
      min: 0,
      value: 0,
    },
    {
      type: "input-array",
      name: "http_path",
      label: "路由",
      items: {
        type: "input-text",
        options: await getMenuHttpPathOptions(),
        required: true,
      },
    },
    {
      type: "tree-select",
      name: "menus",
      label: "菜单",
      searchable: true,
      multiple: true,
      showIcon: false,
      labelField: "title",
      valueField: "id",
      autoCheckChildren: false,
      joinValues: false,
      extractValue: true,
      options: await getMenuTreePermissionsOptions(),
    },
  ];
}

//详情配置
async function detail() {
  return {
    title: "查看详情",
    body: {
      type: "form",
      body: [
        {
          type: "input-text",
          name: "name",
          label: "名称",
          value: "${name}",
          disabled: true,
        },
        {
          type: "input-text",
          name: "slug",
          label: "标识",
          value: "${slug}",
          disabled: true,
        },
        {
          type: "input-text",
          name: "http_method",
          label: "请求方式",
          value: "${http_method}",
          disabled: true,
        },
        {
          type: "input-text",
          name: "http_path",
          label: "路由",
          value: "${http_path}",
          disabled: true,
        },
      ],
    },
  };
}

//筛选配置
async function filter() {
  return {
    title: "筛选",
    mode: "inline",
    controls: [
      { type: "input-text", name: "name", label: "名称" },
      { type: "submit", label: "查询", level: "primary" },
      { type: "reset", label: "重置" },
    ],
  };
}

export const SysPermissionsController = {
  async index(req, res) {
    const query = parse(req.url, true).query;
    if (query._replace === "1") {
      const list = await grid();
      return successResponse(res, {data: list});
    }
    try {
      const query = AdminPermissions.query();
      if (req.query.name) {
        query.where("name", "like", `%${req.query.name}%`);
      }
      const list = await query.paginate(req.query.page, req.query.perPage);
      return successResponse(res, {data: list.items()});
    } catch (error) {
      console.error("获取权限列表失败:", error);
      return errorResponse(res, {msg: "服务器错误，请稍后重试"});
    }
  },
  async edit(req, res) {
    const { id } = req.params;
    if (!id) {
      return errorResponse(res, {msg: "无效的请求参数！"});
    }
    try {
      const permissions = await AdminPermissions.query().with("menus").find(id);
      console.log(permissions);
      return successResponse(res, {data: permissions});
    } catch (error) {
      return sendResponse(res, 500, 1, "服务器错误！");
    }
  },

  async store(req, res) {
    const params = req.body;
    const menu_id = params.menus;
    delete params.menus;

    if (Object.keys(params).length === 0) {
      return errorResponse(res, {msg: "无效的请求参数！"});
    }

    const existPermission = await AdminPermissions.query()
      .where({ name: params.name })
      .first();
    if (existPermission) {
      return errorResponse(res, {msg: "名称已存在！"});
    }

    // 处理 http_method
    if (params.http_method) {
      if (Array.isArray(params.http_method)) {
        params.http_method =
          params.http_method.length > 0 ? params.http_method.join(",") : null;
      }
    } else {
      params.http_method = null;
    }

    // 处理 http_path
    if (params.http_path && Array.isArray(params.http_path)) {
      params.http_path = params.http_path.join(",");
    }
    params.created_at = new Date();
    params.updated_at = new Date();
    try {
      await db.transaction(async (trx) => {
        const result = await AdminPermissions.query()
          .transacting(trx)
          .insert(params);

        // MySQL下 result 是插入的id
        const newPermissionId = result[0];

        if (menu_id) {
          if (Array.isArray(menu_id)) {
            const permissionMenus = menu_id.map((mid) => ({
              permission_id: newPermissionId,
              menu_id: mid,
              created_at: new Date(),
              updated_at: new Date(),
            }));
            await AdminPermissionsMenu.query()
              .transacting(trx)
              .insert(permissionMenus);
          } else {
            await AdminPermissionsMenu.query()
              .transacting(trx)
              .insert({
                permission_id: newPermissionId,
                menu_id,
                created_at: new Date(),
                updated_at: new Date(),
              });
          }
        }
      });

      return successResponse(res, {msg: "添加成功！"});
    } catch (error) {
      return errorResponse(res, {msg: "服务器错误！" + error.message});
    }
  },

  async update(req, res) {
    const { id } = req.params;
    const params = req.body;
    const menu_id = params.menus;
    delete params.menus;

    if (!id || !params || Object.keys(params).length === 0) {
      return errorResponse(res, {msg: "无效的请求参数！"});
    }

    // 处理 http_method 数组
    if (params.http_method && params.http_method.length > 0) {
      let methods = [];
      if (typeof params.http_method === "string") {
        methods = params.http_method.split(",").map((item) => item.trim());
      }
      if (Array.isArray(params.http_method)) {
        methods = params.http_method;
      }
      methods = methods.filter((method) => method !== "ANY");
      params.http_method = methods.join(",");
    } else {
      params.http_method = "ANY";
    }

    delete params.created_at;
    delete params.updated_at;

    // 处理 http_path 数组
    if (params.http_path && Array.isArray(params.http_path)) {
      params.http_path = params.http_path.join(",");
    }

    try {
      // 保存 permission 表
      const result = await AdminPermissions.query()
        .where({ id })
        .update(params);

      if (result) {
        // 如果有 menus_id，保存 admin_permission_menu 表
        if (menu_id) {
          // 删除旧的关联记录
          await AdminPermissionsMenu.query()
            .where({ permission_id: id })
            .delete();

          // 提取菜单 id 数组
          const menuIds = Array.isArray(menu_id)
            ? menu_id
              .map((item) => (typeof item === "object" ? item.id : item))
              .filter((item) => item)
            : menu_id
              .toString()
              .split(",")
              .map((item) => item.trim())
              .filter((item) => item);

          // 批量插入新的关联记录
          if (menuIds.length > 0) {
            const insertData = menuIds.map((menuId) => ({
              permission_id: id,
              menu_id: menuId,
              created_at: new Date(),
              updated_at: new Date(),
            }));
            await AdminPermissionsMenu.query().insert(insertData);
          }
        }

        return successResponse(res, {msg: "保存成功！"});
      } else {
        return errorResponse(res, {msg: "保存失败！"});
      }
    } catch (error) {
      console.error(error);
      return errorResponse(res, {msg: "服务器异常！"});
    }
  },

  async destroy(req, res) {
    return adminCrud.destroy(req, res, AdminPermissions);
  },
};

export async function getPermissionsTreeOptions1() {
  const menus = await AdminPermissions.query().orderBy("custom_order", "asc").get();
  const list = menus.toData();
  const map = {};
  list.forEach((menu) => {
    map[menu.id] = {
      label: menu.name,
      value: menu.id,
      children: [],
    };
  });

  // 然后遍历所有节点，把它挂到父节点的 children 里
  const tree = [];
  list.forEach((menu) => {
    const node = map[menu.id];
    if (menu.parent_id && map[menu.parent_id]) {
      map[menu.parent_id].children.push(node);
    } else {
      // 没有 parent_id 或 parent_id=0 说明是顶层
      tree.push(node);
    }
  });

  return tree;
}

export async function getMenuTreePermissionsOptions(parentId = 0) {
  const menus = await AdminMenus.query().orderBy("custom_order", "asc").get();
  // 递归构建树形结构
  const buildTree = (data, pid = 0) => {
    return data
      .filter((menu) => menu.parent_id === pid)
      .map((menu) => {
        const children = buildTree(data, menu.id);
        if (children.length > 0) {
          menu.children = children;
        }
        return menu;
      });
  };

  // 返回完整树形菜单
  return buildTree(menus.toJSON());
}

export async function getMenuHttpPathOptions() {
  const menus = await AdminMenus.query().select("id", "url").get();
  const list = menus.toData();
  const result = list.map((v) => {
    return {
      label: v.url,
      value: v.url,
    };
  });
  return result;
}
